using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLogManager;
using WJ.DataSender.Service.Commen;
using WJ.DataSender.Service.Models;
using WJ.DataSender.Service.Models.ResultModel;

namespace WJ.DataSender.Service
{
    public class TraceRadarWorker : BackgroundService
    {
        /// <summary>
        /// 消息处理引擎
        /// </summary>
        private readonly IMessageHandle<WjByRadarRequestModel, WjByResultModel> _messageHandle;

        /// <summary>
        /// 上报周期，通过配置文件进行配置
        /// </summary>
        private int period = CacheValues.AppsettingConfig.SendPeriod;
        public TraceRadarWorker(IMessageHandle<WjByRadarRequestModel, WjByResultModel> handle)
        {
            _messageHandle = handle;
        }

        /// <summary>
        /// 开始
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        public override async Task StartAsync(CancellationToken stoppingToken)
        {
            LogHelper.Info($"当前任务-[{WorkType.TraceRadar}]-已经开始");
            await base.StartAsync(stoppingToken);
        }

        /// <summary>
        /// 正在执行
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                LogHelper.Info($"{DateTime.Now}任务正在努力的进行中...");

                await Task.Run(async () =>
                {
                    while (!stoppingToken.IsCancellationRequested)
                    {
                        try
                        {
                            LogHelper.Debug($"{DateTime.Now}-调用毫米波雷达数据上报接口");
                            //调用上报接口
                            if (_messageHandle.StopSend)
                            {
                                LogHelper.Debug($"{_messageHandle.PlatformName}平台{WorkType.TraceRadar.Desc()}设备数据已停止上报！");
                                return;
                            }

                            #region 处理上报内容
                            var content = new WjByRadarRequestModel();
                            if (!CommenLogic.PrefectRequestContent(content))
                            {
                                return;
                            }
                            #endregion
                            var result = await _messageHandle.SendMessageAsync(HttpMethod.Post, content);
                            if (result.StatusCode != (int)ErrorCode.Success)
                            {
                                LogHelper.Error($"{_messageHandle.PlatformName}平台{WorkType.TraceRadar.Desc()}数据上报失败！具体原因：【{result.ErrorMsg}】");
                            }
                            else
                            {
                                LogHelper.Debug($"{_messageHandle.PlatformName}平台{WorkType.TraceRadar.Desc()}设备数据上报成功");
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Fatal($"平台对接过程中出现问题，具体问题需要查看跟踪堆栈内容！{ex.Message}", ex);
                        }
                        // 控制上报频率
                        Thread.Sleep(period);
                    }
                }, stoppingToken);
            }
            catch (Exception ex)
            {

                LogHelper.Fatal("上报毫米波雷达任务出现严重错误！！", ex);
            }

        }

        public override async Task StopAsync(CancellationToken stoppingToken)
        {
            LogHelper.Info("上报毫米波雷达任务已经取消，正常退出！");
            await base.StopAsync(stoppingToken);
        }
    }
}
